import sites from "../sites.js";
async function getWebsites() {
  let webSites = localStorage.getItem("websites") || "[]";
  let newSites = await JSON.parse(webSites);
  let arr = newSites.filter(function (item) {
    return !isWebInArray(item, sites);
  });
  if (arr.length != newSites.length) {
    localStorage.setItem("websites", JSON.stringify(arr));
  }
  return [...sites, ...arr];
}

function getUnStoredWebsites() {
  let webSites = localStorage.getItem("websites") || "[]";
  let arr = JSON.parse(webSites).filter(function (item) {
    return !isWebInArray(item, sites);
  });
  return arr;
}

function isWebInArray(web, array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].url == web.url) {
      return true;
    }
  }
  return false;
}

async function addWebsite(webSite) {
  if (isWebInArray(webSite, sites)) {
    return false;
  }
  //删除之前的
  await removeWebsite(webSite);
  var websites = await getWebsites() || [];
  websites = [webSite, ...websites];
  localStorage.setItem("websites", JSON.stringify(websites));
  return true;
}

function hasWebSite(webSite, src) {
  var websites = src || getWebsites();
  if (websites) {
    for (var i = 0; i < websites.length; i++) {
      if (websites[i].url == webSite.url) {
        return true;
      }
    }
  }
  for (var i = 0; i < sites.length; i++) {
    if (sites[i].url == webSite.url) {
      return true;
    }
  }
  return false;
}

async function removeWebsite(webSite) {
  var websites = await getWebsites() || [];
  websites = websites.filter(function (item) {
    return item.url != webSite.url;
  });
  localStorage.setItem("websites", JSON.stringify(websites));
}

export {
  getWebsites,
  addWebsite,
  hasWebSite,
  removeWebsite,
  getUnStoredWebsites,
};
